<?php

namespace System\Core;

class File
{
    protected $dirPath;
    protected $size;
    protected $type;
    protected $file;

    public function __construct($file)
    {
        $this->file = $file;
        $this->size = Config::get('size','');
        $this->type = Config::get('type','');
        if(!empty($this->type)){
            $this->type = explode(',', $this->type);
        }
        $dir_path = Config::get('dir_path','');
        if (empty($dir_path)) {
            return;
        }
        $arr = explode('/', $dir_path);
        $arrC = [];
        foreach ($arr as $key => $item) {
            if (strpos($item, '{')!==false) {
                $item = str_replace('{', '', $item);
                $item = str_replace('}', '', $item);
                $item = date($item);
            }
            $arrC[] = $item;
        }
        $this->dirPath = implode('/', $arrC);
    }

    public function move()
    {
        $name = $this->file["name"];

        $prefix = md5(time() . rand(1000, 9999) . pathinfo($name, PATHINFO_FILENAME));
        $suffix = pathinfo($name, PATHINFO_EXTENSION);

        $type = $this->file["type"];
        if (!empty($this->type) && !in_array($type, $this->type)) {
            throw new \Exception("Error uploading file!");
        }

        $size = $this->file["size"];
        if (!empty($this->size) && $size > $this->size * 1024 * 1024) {
            throw new \Exception("Error uploading file!");
        }

        $temp = $this->file["tmp_name"];

        $error = $this->file["error"];

        if ($error > 0)

            throw new \Exception("Error uploading file!");

        else {
            $fileName = $prefix . "." . $suffix;
            $dir = $this->dirPath??'uploads/';
            if (!is_dir($dir)) {
                mkdir($dir, 0777, true);
            }

            move_uploaded_file($temp, $dir . "/" . $fileName);
            return $dir . "/" . $fileName;
        }
    }
}
